package multdata.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

import javax.sql.DataSource;

@Configuration
@Slf4j
public class DatabaseConfig {

    @Value("${spring.datasource.stimulate.type}")
    private String dataSouceTypeStimulate;

    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.stimulate")
    public DataSource dataSourceStimulate() {
        DataSourceBuilder builder = DataSourceBuilder.create();
        if (null != dataSouceTypeStimulate) {
            Class type = null;
            try {
                type = Class.forName(dataSouceTypeStimulate);
            } catch (ClassNotFoundException e) {
                log.error("DataSource type配置错误，已重置为默认的DataSource。class not find type=" + dataSouceTypeStimulate);
            }
            builder.type(type);
        }
        DataSource dataSource = builder.build();
        return dataSource;
    }

    @Value("${spring.datasource.zoo.type}")
    private String dataSouceTypeZoo;

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.zoo")
    public DataSource dataSourceZoo() {
        DataSourceBuilder builder = DataSourceBuilder.create();
        if (null != dataSouceTypeZoo) {
            Class type = null;
            try {
                type = Class.forName(dataSouceTypeZoo);
            } catch (ClassNotFoundException e) {
                log.error("DataSource type配置错误，已重置为默认的DataSource。class not find type=" + dataSouceTypeZoo);
            }
            builder.type(type);
        }
        DataSource dataSource = builder.build();
        return dataSource;
    }

    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
//        adapter.setDatabase(Database.MYSQL);
////        adapter.setShowSql(true);
//        adapter.setGenerateDdl(true);
//        adapter.setDatabasePlatform("org.hibernate.dialect.MySQL5Dialect");
        return adapter;
    }
}
